"""
病历管理 API
严格按照原 Flask 项目的接口实现，保持 100% 兼容性
原文件: routes/medical_record_routes.py
遵循 FastAPI 标准流程：使用 CRUD 层 + Schema 层
"""
from typing import Optional, List
from fastapi import APIRouter, Depends, Query, Request
from fastapi.responses import StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
from io import BytesIO
import openpyxl
from openpyxl.styles import Font, Alignment, PatternFill
import urllib.parse

from  core.database import get_db
from  api.deps import get_current_active_doctor
from  models.doctor import Doctor
from  schemas.medical_record import (
    MedicalRecordCreate, 
    MedicalRecordUpdate, 
    MedicalRecordResponse,
    MedicalRecordQueryParams,
    PaginationParams,
    PaginatedMedicalRecordsResponse,
    MedicalRecordBatchExportRequest
)
from  crud import medical_record as crud_medical_record
from  crud import patient as crud_patient

router = APIRouter()


# ============================================
# 注意：具体路由必须在动态路由之前定义！
# 路由匹配顺序：从上到下，第一个匹配的路由会被使用
# ============================================


@router.post("")
async def create_medical_record(
    record_in: MedicalRecordCreate,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    创建病历
    原接口: POST /api/medical-records
    需要JWT认证
    使用 CRUD 层创建
    """
    try:
        # 验证患者是否存在且属于当前医生
        patient = await crud_patient.get(db, id=record_in.patient_id)
        
        if not patient or patient.status != 1:
            return {
                "message": "患者不存在或您无权访问",
                "code": 1
            }
        
        # 权限检查
        if patient.doctor_id != current_doctor.id:
            return {
                "message": "患者不存在或您无权访问",
                "code": 1
            }
        
        # 使用 CRUD 层创建病历
        record = await crud_medical_record.create(db, obj_in=record_in)
        await db.commit()
        
        return {
            "message": "病历创建成功",
            "id": str(record.id),
            "code": 0
        }
        
    except Exception as e:
        await db.rollback()
        return {
            "message": f"创建失败: {str(e)}",
            "code": 1
        }


@router.get("/medical-records/export")
async def export_medical_records_query(
    patient_id: Optional[str] = Query(None, description="患者ID"),
    stroke_location: Optional[str] = Query(None, description="卒中部位"),
    paralysis_location: Optional[str] = Query(None, description="瘫痪部位"),
    patient_name: Optional[str] = Query(None, description="患者姓名"),
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    导出病历列表（查询）
    原接口: GET /api/medical-records/medical-records/export
    需要JWT认证
    使用 CRUD 层的 query_by_conditions 方法
    """
    try:
        # 转换 patient_id
        pid = None
        if patient_id:
            try:
                pid = int(patient_id)
            except:
                pass
        
        # 使用 CRUD 层条件查询（升序排序）
        records, _ = await crud_medical_record.query_by_conditions(
            db,
            patient_id=pid,
            patient_name=patient_name,
            stroke_location=stroke_location,
            paralysis_location=paralysis_location,
            order_by_desc=False  # 升序排序
        )
        
        # 使用 Schema 转换为 Flask 格式
        records_data = [
            MedicalRecordResponse.model_validate(r).to_flask_format()
            for r in records
        ]
        
        return {
            "message": "导出病历列表成功",
            "data": records_data,
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": f"导出病历列表失败: {str(e)}",
            "code": 1
        }


@router.get("/all")
async def get_all_medical_records(
    patient_id: Optional[str] = Query(None, description="患者ID"),
    strokeLocation: Optional[str] = Query(None, description="卒中部位"),
    paralysisLocation: Optional[str] = Query(None, description="瘫痪部位"),
    patientName: Optional[str] = Query(None, description="患者姓名（模糊查询）"),
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    获取所有病历（不分页）
    原接口: GET /api/medical-records/all
    需要JWT认证
    使用 CRUD 层的 query_by_conditions 方法
    """
    try:
        # 转换 patient_id
        pid = None
        if patient_id:
            try:
                pid = int(patient_id)
            except:
                pass
        
        # 使用 CRUD 层条件查询（升序排序）
        records, _ = await crud_medical_record.query_by_conditions(
            db,
            patient_id=pid,
            patient_name=patientName,
            stroke_location=strokeLocation,
            paralysis_location=paralysisLocation,
            order_by_desc=False  # 升序排序
        )
        
        # 使用 Schema 转换为 Flask 格式
        records_data = [
            MedicalRecordResponse.model_validate(r).to_flask_format()
            for r in records
        ]
        
        return {
            "message": "获取病历列表成功",
            "data": records_data,
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1
        }


@router.get("/wx-patient/{patient_id}")
async def get_wx_medical_records_by_patient(
    patient_id: str,
    db: AsyncSession = Depends(get_db)
):
    """
    患者获取自己的病历列表（微信小程序）
    原接口: GET /api/medical-records/wx-patient/<patient_id>
    不需要JWT认证
    使用 CRUD 层的 get_by_patient 方法
    """
    try:
        # 转换 ID
        try:
            patient_id_int = int(patient_id)
        except:
            return {
                "message": "无效的患者ID",
                "code": 1
            }
        
        # 使用 CRUD 层查询
        records = await crud_medical_record.get_by_patient(
            db,
            patient_id=patient_id_int
        )
        
        # 使用 Schema 转换为 Flask 格式
        records_data = [
            MedicalRecordResponse.model_validate(r).to_flask_format()
            for r in records
        ]
        
        return {
            "message": "获取病历列表成功",
            "data": records_data,
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1
        }


@router.get("/wx-records")
async def wx_get_medical_records(
    page: int = Query(1, ge=1, description="页码"),
    per_page: int = Query(10, ge=1, le=100, description="每页数量"),
    patient_id: Optional[str] = Query(None, description="患者ID"),
    stroke_location: Optional[str] = Query(None, description="卒中部位"),
    paralysis_location: Optional[str] = Query(None, description="瘫痪部位"),
    patientName: Optional[str] = Query(None, description="患者姓名（模糊查询）"),
    db: AsyncSession = Depends(get_db)
):
    """
    患者获取病历列表（分页，微信小程序）
    原接口: GET /api/medical-records/wx-records
    不需要JWT认证
    使用 Schema + CRUD 层标准流程
    """
    try:
        # 使用 PaginationParams Schema 计算 skip
        pagination = PaginationParams(page=page, per_page=per_page)
        
        # 转换 patient_id
        pid = None
        if patient_id:
            try:
                pid = int(patient_id)
            except:
                pass
        
        # 使用 CRUD 层条件查询（降序排序）
        records, total = await crud_medical_record.query_by_conditions(
            db,
            patient_id=pid,
            patient_name=patientName,
            stroke_location=stroke_location,
            paralysis_location=paralysis_location,
            skip=pagination.skip,
            limit=per_page,
            order_by_desc=True  # 降序排序
        )
        
        # 使用 Schema 转换为 Flask 格式
        records_data = [
            MedicalRecordResponse.model_validate(r).to_flask_format()
            for r in records
        ]
        
        # 使用 PaginatedMedicalRecordsResponse 创建分页响应
        paginated_response = PaginatedMedicalRecordsResponse.create(
            records=records_data,
            total=total,
            page=page,
            per_page=per_page
        )
        
        return {
            "message": "获取病历列表成功",
            "data": paginated_response.model_dump(),
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1
        }


@router.get("/wx-records/{record_id}")
async def wx_get_medical_record(
    record_id: str,
    db: AsyncSession = Depends(get_db)
):
    """
    患者获取病历详情（微信小程序）
    原接口: GET /api/medical-records/wx-records/<record_id>
    不需要JWT认证
    使用 CRUD 层的 get 方法
    """
    try:
        # 转换 ID
        try:
            record_id_int = int(record_id)
        except:
            return {
                "message": "无效的病历ID",
                "code": 1
            }
        
        # 使用 CRUD 层获取病历
        record = await crud_medical_record.get(db, id=record_id_int)
        print("record!!", record)
        if not record or record.status != 1:
            return {
                "message": "病历不存在",
                "code": 1
            }
        
        # 验证患者是否存在
        patient = await crud_patient.get(db, id=record.patient_id)
        
        if not patient or patient.status != 1:
            return {
                "message": "您无权访问此病历",
                "code": 1
            }
        
        # 使用 Schema 转换为 Flask 格式
        record_data = MedicalRecordResponse.model_validate(record).to_flask_format()
        # 新增：包含数据库中新加的 treatment 字段（治疗时间轴）
        # try:
        #     record_data['treatment'] = record.treatment or []
        # except Exception:
        #     record_data['treatment'] = []
        # print("record_data", record_data)
        return {
            "message": "获取病历详情成功",
            "data": record_data,
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": "无效的病历ID",
            "code": 1
        }


def create_medical_records_excel(medical_records: List) -> openpyxl.Workbook:
    """
    创建病历信息Excel文件
    辅助函数，不直接操作数据库
    """
    # 创建工作簿和工作表
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "病历信息"

    # 设置表头
    headers = [
        '序号', '患者姓名', '初步诊断', '发病日期', '病程天数', 'NIHSS评分',
        '卒中部位', '瘫痪部位', '是否手术', '手术类型', '是否有动脉狭窄',
        '动脉类型', '颈部血管超声', '是否有语言障碍', '障碍类型',
        '创建时间', '更新时间'
    ]
    
    # 写入表头
    for col, header in enumerate(headers, 1):
        cell = ws.cell(row=1, column=col, value=header)
        cell.font = Font(bold=True, color="FFFFFF")
        cell.fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")
        cell.alignment = Alignment(horizontal="center", vertical="center")

    # 写入数据
    for row_idx, record in enumerate(medical_records, 2):
        # 处理数组类型的字段，转换为字符串
        initial_diagnosis = ', '.join(record.get('initialDiagnosis', [])) if isinstance(record.get('initialDiagnosis'), list) else record.get('initialDiagnosis', '')
        surgery_types = ', '.join(record.get('surgeryTypes', [])) if isinstance(record.get('surgeryTypes'), list) else record.get('surgeryTypes', '')
        artery_types = ', '.join(record.get('arteryTypes', [])) if isinstance(record.get('arteryTypes'), list) else record.get('arteryTypes', '')
        
        data = [
            row_idx - 1,  # 序号
            record.get('patientName', ''),
            initial_diagnosis,
            record.get('onsetDate', ''),
            record.get('courseDays', ''),
            record.get('nihssScore', ''),
            record.get('strokeLocation', ''),
            record.get('paralysisLocation', ''),
            '是' if record.get('hasSurgery') else '否',
            surgery_types,
            '是' if record.get('hasArteryStenosis') else '否',
            artery_types,
            record.get('neckVesselUltrasound', ''),
            '是' if record.get('languageDisorder') else '否',
            record.get('disorderType', ''),
            record.get('createdAt', ''),
            record.get('updatedAt', '')
        ]
        
        for col, value in enumerate(data, 1):
            cell = ws.cell(row=row_idx, column=col, value=value)
            cell.alignment = Alignment(horizontal="center", vertical="center")

    # 调整列宽
    for column in ws.columns:
        max_length = 0
        column_letter = column[0].column_letter
        for cell in column:
            try:
                if len(str(cell.value)) > max_length:
                    max_length = len(str(cell.value))
            except:
                pass
        adjusted_width = min(max_length + 2, 25)
        ws.column_dimensions[column_letter].width = adjusted_width

    return wb


@router.post("/export")
async def export_medical_records_batch(
    batch_request: MedicalRecordBatchExportRequest,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    批量导出病历（Excel）
    原接口: POST /api/medical-records/export
    需要JWT认证
    使用 Schema 验证请求 + CRUD 层查询
    """
    try:
        # Schema 已经自动验证并转换了 record_ids
        object_ids = batch_request.record_ids
        
        # 使用 CRUD 层批量查询病历
        medical_records = await crud_medical_record.get_by_ids(
            db,
            record_ids=object_ids
        )
        
        # 验证病历归属权限（检查患者是否属于当前医生）
        validated_records = []
        for record in medical_records:
            patient = await crud_patient.get(db, id=record.patient_id)
            if patient and patient.doctor_id == current_doctor.id and patient.status == 1:
                # 使用 Schema 转换为字典格式
                record_dict = MedicalRecordResponse.model_validate(record).to_flask_format()
                validated_records.append(record_dict)
        
        if not validated_records:
            return {
                "message": "未找到可导出的病历信息或您无权访问",
                "code": 1
            }
        
        # 创建Excel文件
        wb = create_medical_records_excel(validated_records)
        
        # 保存到内存
        output = BytesIO()
        wb.save(output)
        output.seek(0)
        
        # 生成文件名
        from datetime import datetime
        filename = f"medical_records_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        filename_utf8 = f"病历信息导出_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        
        # 使用URL编码支持中文文件名
        encoded_filename = urllib.parse.quote(filename_utf8.encode('utf-8'))
        
        # 返回文件流
        return StreamingResponse(
            BytesIO(output.getvalue()),
            media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            headers={
                'Content-Disposition': f'attachment; filename="{filename}"; filename*=UTF-8\'\'{encoded_filename}'
            }
        )
        
    except Exception as e:
        return {
            "message": f"导出失败: {str(e)}",
            "code": 1
        }


@router.get("/export/all")
async def export_all_medical_records(
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    导出所有病历（Excel）
    原接口: GET /api/medical-records/export/all
    需要JWT认证
    使用 CRUD 层的 get_by_patient_ids 方法
    """
    try:
        # 首先获取当前医生的所有患者ID
        from sqlalchemy import select
        from  models.patient import Patient
        
        patients_query = select(Patient.id).where(
            Patient.doctor_id == current_doctor.id,
            Patient.status == 1
        )
        patients_result = await db.execute(patients_query)
        patient_ids = [pid for pid, in patients_result.all()]
        
        if not patient_ids:
            return {
                "message": "没有患者信息，无法导出病历",
                "code": 1
            }
        
        # 使用 CRUD 层查询这些患者的所有病历
        medical_records = await crud_medical_record.get_by_patient_ids(
            db,
            patient_ids=patient_ids
        )
        
        if not medical_records:
            return {
                "message": "没有病历信息可导出",
                "code": 1
            }
        
        # 使用 Schema 转换为字典格式
        records_data = [
            MedicalRecordResponse.model_validate(r).to_flask_format()
            for r in medical_records
        ]
        
        # 创建Excel文件
        wb = create_medical_records_excel(records_data)
        
        # 保存到内存
        output = BytesIO()
        wb.save(output)
        output.seek(0)
        
        # 生成文件名
        from datetime import datetime
        filename = f"all_medical_records_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        filename_utf8 = f"全部病历信息_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        
        # 使用URL编码支持中文文件名
        encoded_filename = urllib.parse.quote(filename_utf8.encode('utf-8'))
        
        # 返回文件流
        return StreamingResponse(
            BytesIO(output.getvalue()),
            media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            headers={
                'Content-Disposition': f'attachment; filename="{filename}"; filename*=UTF-8\'\'{encoded_filename}'
            }
        )
        
    except Exception as e:
        return {
            "message": f"导出失败: {str(e)}",
            "code": 1
        }


# ============================================
# 动态路由：放在最后，避免拦截具体路由
# ============================================


@router.get("")
async def get_medical_records(
    page: int = Query(1, ge=1, description="页码"),
    per_page: int = Query(10, ge=1, le=100, description="每页数量"),
    patient_id: Optional[str] = Query(None, description="患者ID"),
    stroke_location: Optional[str] = Query(None, description="卒中部位"),
    paralysis_location: Optional[str] = Query(None, description="瘫痪部位"),
    patientName: Optional[str] = Query(None, description="患者姓名（模糊查询）"),
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    获取病历列表（分页+查询）
    原接口: GET /api/medical-records
    需要JWT认证
    使用 Schema + CRUD 层标准流程
    """
    try:
        # 使用 PaginationParams Schema 计算 skip
        pagination = PaginationParams(page=page, per_page=per_page)
        print("patient-id", patient_id)
        # 转换 patient_id
        pid = None
        if patient_id:
            try:
                pid = int(patient_id)
            except:
                pass
        
        # 使用 CRUD 层条件查询（降序排序）
        records, total = await crud_medical_record.query_by_conditions(
            db,
            patient_id=pid,
            patient_name=patientName,
            stroke_location=stroke_location,
            paralysis_location=paralysis_location,
            skip=pagination.skip,
            limit=per_page,
            order_by_desc=True  # 降序排序
        )
        
        # 使用 Schema 转换为 Flask 格式
        records_data = [
            MedicalRecordResponse.model_validate(r).to_flask_format()
            for r in records
        ]
        
        # 使用 PaginatedMedicalRecordsResponse 创建分页响应
        paginated_response = PaginatedMedicalRecordsResponse.create(
            records=records_data,
            total=total,
            page=page,
            per_page=per_page
        )
        
        return {
            "message": "获取病历列表成功",
            "data": paginated_response.model_dump(),
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1
        }


@router.get("/{record_id}")
async def get_medical_record(
    record_id: str,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    获取病历详情
    原接口: GET /api/medical-records/<record_id>
    需要JWT认证
    使用 CRUD 层的 get 方法
    """
    try:
        # 转换 ID
        try:
            record_id_int = int(record_id)
        except:
            return {
                "message": "无效的病历ID",
                "code": 1
            }
        
        # 使用 CRUD 层获取病历
        record = await crud_medical_record.get(db, id=record_id_int)
        
        if not record or record.status != 1:
            return {
                "message": "病历不存在",
                "code": 1
            }
        
        # 验证患者是否属于当前医生
        patient = await crud_patient.get(db, id=record.patient_id)
        
        if not patient or patient.status != 1:
            return {
                "message": "您无权访问此病历",
                "code": 1
            }
        
        # 权限检查
        if patient.doctor_id != current_doctor.id:
            return {
                "message": "您无权访问此病历",
                "code": 1
            }
        
        # 使用 Schema 转换为 Flask 格式
        record_data = MedicalRecordResponse.model_validate(record).to_flask_format()
        
        return {
            "message": "获取病历详情成功",
            "data": record_data,
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1
        }


# -----------------------------
# 新增：治疗情况相关接口
# -----------------------------
from pydantic import BaseModel
from datetime import datetime, timezone

class TreatmentCreate(BaseModel):
    title: str


@router.get("/{record_id}/treatments")
async def get_treatments(
    record_id: str,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    获取指定病历的治疗情况列表
    返回格式: [{"title": "xxx", "time": "YYYY-MM-DD HH:MM:SS"}, ...]
    需要JWT认证，且只能由归属医生查看
    """
    try:
        try:
            record_id_int = int(record_id)
        except:
            return {"message": "无效的病历ID", "code": 1}

        # 获取病历
        record = await crud_medical_record.get(db, id=record_id_int)
        if not record or record.status != 1:
            return {"message": "病历不存在", "code": 1}

        # 验证患者是否属于当前医生
        patient = await crud_patient.get(db, id=record.patient_id)
        if not patient or patient.status != 1:
            return {"message": "您无权访问此病历", "code": 1}
        if patient.doctor_id != current_doctor.id:
            return {"message": "您无权访问此病历", "code": 1}

        history = record.treatment_history or []
        # 规范化输出，确保每项包含 title 和 time
        result = []
        for item in history:
            if not isinstance(item, dict):
                continue
            title = item.get('title') or item.get('name') or ''
            time = item.get('time') or item.get('created_at') or ''
            result.append({"title": title, "time": time})

        return {"message": "获取治疗情况成功", "data": result, "code": 0}

    except Exception as e:
        return {"message": f"服务器错误: {str(e)}", "code": 1}


@router.post("/{record_id}/treatments")
async def add_treatment(
    record_id: str,
    payload: TreatmentCreate,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    为指定病历新增一条治疗情况（title），后端会将记录追加到 treatment_history 中，并返回新的列表
    请求体: {"title": "治疗名称"}
    需要JWT认证，且只能由归属医生操作
    """
    try:
        try:
            record_id_int = int(record_id)
        except:
            return {"message": "无效的病历ID", "code": 1}

        # 获取病历
        record = await crud_medical_record.get(db, id=record_id_int)
        if not record or record.status != 1:
            return {"message": "病历不存在", "code": 1}

        # 验证患者是否属于当前医生
        patient = await crud_patient.get(db, id=record.patient_id)
        if not patient or patient.status != 1:
            return {"message": "您无权操作此病历", "code": 1}
        if patient.doctor_id != current_doctor.id:
            return {"message": "您无权操作此病历", "code": 1}

        # 追加治疗记录
        new_item = {
            "title": payload.title,
            "time": datetime.now(timezone.utc).isoformat() 
        }
        
        # 使用原子 SQL 更新 JSONB 字段，避免 ORM 突变跟踪问题
        import json
        from sqlalchemy import text
        # 使用 CAST(:new_item AS jsonb) 替代 :new_item::jsonb，避免与 "::jsonb" 语法冲突导致 asyncpg 参数解析错误
        update_query = text("""
            UPDATE medical_records
            SET treatment_history = COALESCE(treatment_history, '[]'::jsonb) || CAST(:new_item AS jsonb)
            WHERE id = :record_id
        """)
        
        await db.execute(update_query, {
            "new_item": json.dumps([new_item]),
            "record_id": record_id_int
        })
        
        await db.commit()
        
        # 重新获取记录以返回更新后的数据
        record = await crud_medical_record.get(db, id=record_id_int)

        return {"message": "新增治疗情况成功", "data": record.treatment_history or [], "code": 0}

    except Exception as e:
        await db.rollback()
        return {"message": f"新增失败: {str(e)}", "code": 1}

@router.get("/wx-records/{record_id}/treatments")
async def wx_get_treatments(
    record_id: str,
    db: AsyncSession = Depends(get_db)
):
    """
    微信端：获取指定病历的治疗情况列表（不需要 JWT 认证）
    返回格式: [{"title": "xxx", "time": "YYYY-MM-DDTHH:MM:SSZ"}, ...]
    只做病历和患者存在性检查，不做医生权限校验
    """
    try:
        try:
            record_id_int = int(record_id)
        except:
            return {"message": "无效的病历ID", "code": 1}

        # 获取病历
        record = await crud_medical_record.get(db, id=record_id_int)
        if not record or record.status != 1:
            return {"message": "病历不存在", "code": 1}

        # 验证患者是否存在（微信端不做医生权限校验）
        patient = await crud_patient.get(db, id=record.patient_id)
        if not patient or patient.status != 1:
            return {"message": "您无权访问此病历", "code": 1}

        # 支持新旧字段：treatment (新) 与 treatment_history (旧)
        result = []

        # 优先使用新的 treatment 字段（如果存在），然后追加旧的 treatment_history 做兼容
        treatments_new = getattr(record, "treatment", None) or []
        treatments_old = getattr(record, "treatment_history", None) or []

        for item in treatments_new + treatments_old:
            if not isinstance(item, dict):
                continue
            title = item.get("title") or item.get("name") or ""
            time = item.get("time") or item.get("created_at") or ""
            result.append({"title": title, "time": time})

        return {"message": "获取治疗情况成功", "data": result, "code": 0}

    except Exception as e:
        return {"message": f"服务器错误: {str(e)}", "code": 1}


@router.put("/{record_id}")
async def update_medical_record(
    record_id: str,
    record_update: MedicalRecordUpdate,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    更新病历
    原接口: PUT /api/medical-records/<record_id>
    需要JWT认证
    使用 CRUD 层的 get 方法获取，直接更新
    """
    try:
        # 转换 ID
        try:
            record_id_int = int(record_id)
        except:
            return {
                "message": "无效的病历ID",
                "code": 1
            }
        
        # 使用 CRUD 层获取病历
        record = await crud_medical_record.get(db, id=record_id_int)
        
        if not record or record.status != 1:
            return {
                "message": "病历不存在",
                "code": 1
            }
        
        # 验证患者是否属于当前医生
        patient = await crud_patient.get(db, id=record.patient_id)
        
        if not patient or patient.status != 1:#患者不存在
            return {
                "message": "您无权修改此病历,患者不存在",
                "code": 1
            }
        
        # 权限检查
        if patient.doctor_id != current_doctor.id:#医生不匹配：病人的医生id与当前医生的id不匹配
            return {
                "message": "您无权修改此病历!!!",
                "code": 1
            }
        
        # 更新病历
        from datetime import datetime, timezone
        update_data = record_update.model_dump(exclude_unset=True)
        update_data["updated_at"] = datetime.now(timezone.utc)
        
        for key, value in update_data.items():
            setattr(record, key, value)
        
        db.add(record)
        await db.commit()
        
        return {
            "message": "病历更新成功",
            "code": 0
        }
        
    except Exception as e:
        await db.rollback()
        return {
            "message": f"更新失败: {str(e)}",
            "code": 1
        }


@router.delete("/{record_id}")
async def delete_medical_record(
    record_id: str,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    删除病历（软删除）
    原接口: DELETE /api/medical-records/<record_id>
    需要JWT认证
    使用 CRUD 层的 get 方法获取，直接软删除
    """
    try:
        # 转换 ID
        try:
            record_id_int = int(record_id)
        except:
            return {
                "message": "无效的病历ID",
                "code": 1
            }
        
        # 使用 CRUD 层获取病历
        record = await crud_medical_record.get(db, id=record_id_int)
        
        if not record or record.status != 1:
            return {
                "message": "病历不存在",
                "code": 1
            }
        
        # 验证患者是否属于当前医生
        patient = await crud_patient.get(db, id=record.patient_id)
        
        if not patient or patient.status != 1:
            return {
                "message": "您无权删除此病历",
                "code": 1
            }
        
        # 权限检查
        if patient.doctor_id != current_doctor.id:
            return {
                "message": "您无权删除此病历",
                "code": 1
            }
        
        # 软删除
        from datetime import datetime, timezone
        record.status = 0
        record.updated_at = datetime.now(timezone.utc)
        db.add(record)
        await db.commit()
        
        return {
            "message": "病历删除成功",
            "code": 0
        }
        
    except Exception as e:
        await db.rollback()
        return {
            "message": f"删除失败: {str(e)}",
            "code": 1
        }
